package com.ceba.test.modules.signvisual.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;

import com.ceba.base.utils.Base64FileUtils;
import com.ceba.base.web.response.IResult;
import com.ceba.base.web.service.IBaseService;
import com.ceba.cebautils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.enums.ResultStatusEnum;
import com.ceba.test.base.enums.StampTypeEnum;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.modules.admin.entity.GStamp;
import com.ceba.test.modules.signvisual.cache.CreateStampCache;
import com.ceba.test.modules.signvisual.entity.CreateStamp;
import com.ceba.test.modules.signvisual.entity.HandWriteSignRequest;
import com.ceba.test.modules.signvisual.entity.HandWriteSignResponse;

import abc.ID;


@SuppressWarnings("restriction")
public class ThirdCustomSignService  extends IBaseService {
	static Logger logger = LoggerFactory.getLogger(ThirdCustomSignService.class);



	/**
	 * 手写请求
	 * @return
	 */
	public IResult handWriteRequest(String signPageKey) {
		CreateStamp createStamp=CreateStampCache.getInstance().get(signPageKey);
		if(createStamp == null){
			createStamp=new CreateStamp();
			CreateStampCache.getInstance().put(signPageKey, createStamp);
		}
		createStamp.setQrcodeIsClose(true);
		createStamp.setNowTime(new Date());
		createStamp.setStartTime(new Date());

		return null;
	}
	/**
	 * 上传base64
	 * @param request
	 * @return
	 */
	public IResult handWriteUpload(HandWriteSignRequest request,String imgFilePath,String imgVerFilePath ) {

		IResult iResult=new IResult();
		String result=saveBase64(request.getBase64(),request.getSignPageKey(),request.getType(),request.getName(),imgFilePath,imgVerFilePath);
		if(StringUtils.isNotBlank(result)){
			iResult.setMessage(result);
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
		}else{
			iResult.setMessage(ResourceUtils.getMessage("HANDWRITTEN_UPLOAD_SUCCESS"));
			//HAND_WRITE_UPLOAD_SUCESS=上传成功
			iResult.setResultCode(ResultStatusEnum.CG.getCode());
		}
		return iResult;
	}





	/**
	 * 请求章
	 * @param signPageKey
	 * @return
	 */

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public IResult stampRequest(String signPageKey) {
		CreateStamp createStamp=CreateStampCache.getInstance().get(signPageKey);
		HandWriteSignResponse handWriteSignResponse=new HandWriteSignResponse();
		if(createStamp.getQrcodeIsClose() != null && createStamp.getQrcodeIsClose()){
			handWriteSignResponse.setAction(HandWriteSignResponse.Action.COLSE_QRCODE_PAGE);//关闭手写页面
			createStamp.setQrcodeIsClose(false);
		}else if(createStamp.getUploadBaseIsClose() != null && createStamp.getUploadBaseIsClose()){//手写签名页面已经关闭，不能在请求签章
			handWriteSignResponse.setAction(HandWriteSignResponse.Action.CLOSE_STAMP_REQUEST);//关闭签章请求
			createStamp.setUploadBaseIsClose(false);
		}else if(CollectionUtils.isNotEmpty(createStamp.getUploadStampList())){
			List<GStamp> stampList=createStamp.getUploadStampList();
			handWriteSignResponse.setStampList(stampList);
			if(CollectionUtils.isEmpty(createStamp.getResultStampList())){
				createStamp.setResultStampList(new ArrayList());
			}
			createStamp.setUploadStampList(new ArrayList<>());
			createStamp.getResultStampList().addAll(stampList);
			handWriteSignResponse.setAction(HandWriteSignResponse.Action.RETURN_SIGN);//接收签章
		}else{
			handWriteSignResponse.setAction(HandWriteSignResponse.Action.NO_OPERA);//关闭签章请求
		}
		IResult iResult=new IResult();
		iResult.setData(handWriteSignResponse);
		iResult.setResultCode(ResultStatusEnum.CG.getCode());
		return iResult;
	}




	/**
	 * 关闭手写页面
	 * @param request
	 * @return
	 */
	public IResult handWriteClose(HandWriteSignRequest request) {
		CreateStamp createStamp=CreateStampCache.getInstance().get(request.getSignPageKey());
		createStamp.setSignPageIsClose(true);
		IResult iResult = new IResult();
		iResult.setResultCode(ResultStatusEnum.CG.getCode());
		return iResult;

	}



	public String saveBase64(String base64, String signPageKey,String type,String name,String imgFilePath,String imgVerFilePath) {
		if(!StringUtils.isNotEmpty(base64)){
			String message=ResourceUtils.getMessage("MODULES_UPLOAD_PICTURE_EMPTY");
			logger.info(message);
			return message;
		}
		if(!StringUtils.isNotEmpty(signPageKey)){
			//WORKFLOW_SAVE_IMAGE_FLAIE=保存图片失败
			String message=ResourceUtils.getMessage("MODULES_SAVE_PICTURE_FAILURE");
			logger.info(message);
			return message;
		}

//		IUser uUser=Context.getUser();
		CreateStamp createStamp=CreateStampCache.getInstance().get(signPageKey);


		if(createStamp.getSignPageIsClose() != null && createStamp.getSignPageIsClose()){
			//WORKFLOW_SIGN_PAGE_CLOSE=签名页面已经关闭
			String message=ResourceUtils.getMessage("MODULES_SIGNATURE_PAGE_BEEN_CLOSED");
			logger.info(message);
			return message;
		}

		if(createStamp.getUploadBaseIsClose() != null && createStamp.getUploadBaseIsClose()){
			//WORKFLOW_UPLOAD_PAGE_CLOSE=上传页面已经关闭
			String message=ResourceUtils.getMessage("MODULES_UPLOAD_PAGE_BEEN_CLOSED");
			logger.info(message);
			return message;
		}


		if(MapUtils.isEmpty(createStamp.getBaseMap())){
			createStamp.setBaseMap(new HashMap<>());
		}

		if(StringUtils.isNotEmpty(createStamp.getBaseMap().get(base64))){
			//WORKFLOW_HAND_WRITE_SIGN_IMAGE_AGAIN=请不要重复上传图片
			String message=ResourceUtils.getMessage("MODULES_PLEASE_REPORT_UPLOADS");
			logger.info(message);
			return message;
		}
		//虚拟路径存储图片
//		String imgFilePath=CebaPathUtil.getPhysicalTempDirPath()+ID.getGuid()+".png";
		int totalStamp=0;
		if(CollectionUtils.isNotEmpty(createStamp.getResultStampList()) && CollectionUtils.isNotEmpty(createStamp.getUploadStampList())){
			totalStamp=createStamp.getResultStampList().size()+createStamp.getUploadStampList().size();
		}else if(CollectionUtils.isNotEmpty(createStamp.getResultStampList())){
			totalStamp=createStamp.getResultStampList().size();
		}else if(CollectionUtils.isNotEmpty(createStamp.getUploadStampList())){
			totalStamp=createStamp.getUploadStampList().size();
		}
		if(StringUtils.isBlank(name)){
			name="admin"+totalStamp;
		}
		Base64FileUtils.string2Image(getBase64PurifyData(base64), imgFilePath);
		GStamp stamp=null;
		try {
			stamp = imagePathToStamp(imgVerFilePath,name,imgFilePath);
			stamp.setCorFlag(type);
		} catch (IOException e) {
			//WORKFLOW_READ_IMAGE_FLAIE=读取图片失败
			String message=ResourceUtils.getMessage("MODULES_READING_PICTURE_FAILURE");
			logger.debug(message+":"+e.getMessage());
			return message;
		}
		if(CollectionUtils.isEmpty(createStamp.getResultStampList())){
			createStamp.setUploadStampList(new ArrayList<GStamp>());
		}
		createStamp.getUploadStampList().add(stamp);
		createStamp.getBaseMap().put(base64, stamp.getId());
		createStamp.setNowTime(new Date());
		//saveStamp(stamp,uUser.getId());
		stamp.setFilePath(stamp.getFilePath());
		return null;
	}

	/**
	 * 取得base64净化数据
	 * @return
	 */
	public String getBase64PurifyData(String base64){
		String[] base64s=StringUtils.split(base64,",");
		if(base64s.length == 2){
			return base64s[1];
		}
		return null;
	}





	/**
	 * 将图片转换为stamp
	 * @param imgFilePath
	 * @return
	 */
	public GStamp imagePathToStamp(String imgVerFilePath,String imgName,String imgFilePath)throws IOException{
		BufferedImage bufferedImage=ImageIO.read(new File(imgFilePath));
		GStamp stamp=new GStamp();
		stamp.setId(ID.getGuid());
		float imgWidth = bufferedImage.getWidth();//图片的宽度
		int imgHeight = bufferedImage.getHeight();//图片的高度
		stamp.setImgHeight(imgHeight+"");
		stamp.setImgWidth(imgWidth+"");
		stamp.setFilePath(imgVerFilePath);
		stamp.setCorFlag(StampTypeEnum.USER_COR_STAMP_FLAG.getType());
		stamp.setCorStampName(imgName);
		stamp.setStampPage("1");
		stamp.setUpdateTime(DateUtil.getNowTime(null));
		stamp.setUpdateUser(CebaConfig.ANDMIN_USER_ID);
		//读取图片失败
		return stamp;
	}



}
